<template>
    <ElDialog 
    v-model="visible" 
    :title="'修改邮箱'" 
    :width="screenTypeWidth"
    :buttonText="'提交'"
    :submitBtnVisible="true"
    @handleClick="handleClick"
    @resetForm="resetForm">
        <template #main>
            <el-form 
            :model="form" 
            size="large"
            :rules="rules"
            ref="formRef">
                <el-form-item label="" prop="eMail">
                    <el-input v-model.trim="form.eMail" placeholder="邮箱"></el-input>
                </el-form-item>
                <el-form-item label="" prop="verificationCode" class="code-item">
                    <el-input v-model.trim="form.verificationCode" placeholder="验证码">
                        <template #append>
                            <el-button type="" :disabled="codeDisabled" @click="onSendCode">{{emailCode}}</el-button>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="" prop="password">
                    <el-input type="password" v-model.trim="form.password"  placeholder="密码"></el-input>
                </el-form-item>
            </el-form>
        </template>
    </ElDialog>
</template>

<script setup>
import ElDialog from '@/components/system/el-dialog/el-dialog.vue';
import { reactive } from 'vue';
import { SEND_EMAIL_TYPE } from '@/constants/system/email-const';
import { countDown, clearCountDown } from '@/utils/countdown-util';
import { loginApi } from '@/api/system/login/login-api';
import { useUserStore } from '@/store/system/user';
import { ElMessage, ElMessageBox } from 'element-plus';
import { usersApi } from '@/api/system/users/users-api';
import { aes } from '@/utils/crypto-util';
import { storeToRefs } from 'pinia';
import { websiteStore } from '@/store/system/website';
const { screenType } = storeToRefs(websiteStore());
// ========================= 接收值 =========================
const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
})

// ========================= 计算属性 =========================
// 使用计算属性模拟双向绑定
const visible = computed({
    get() {
        return props.visible
    },
    set(value) {
        emit('update:visible', value)
    }
});

// 移动端适配
const screenTypeWidth = computed(() => {
    if(screenType.value === 'extraSmall-screen') {
        return '90%';
    }else if(screenType.value === 'small-screen') {
        return '70%';
    }else if(screenType.value === 'medium-screen') {
        return '42%';
    }else {
        return '30%';
    }
});

// ========================= 向父组件传值 =========================
const emit = defineEmits(['update:visible']);
// 提交表单
const form = reactive({
    id:'',                  // 用户主键id
    eMail:'',               // 邮箱
    password:'',            // 密码
    verificationCode:'',    // 验证码
});
// 表单控制
const rules = reactive({
    eMail: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ],
    verificationCode: [
        { required: true, message: '请输入验证码', trigger: 'change' }
    ],
});
let { id } = useUserStore();
const formRef = ref();
function handleClick() {            // 点击确定
    formRef.value.validate(async (valid) => {
        try {
            if(valid) {
                let newform = {};
                newform = {...newform, ...form};
                newform.id = id;
                newform.password = aes.en(newform.password);
                const res = await usersApi.resetEmail(newform);
                if(res.meta.status !== 200) throw new Error(res.meta.msg);
                ElMessage.success('修改成功');
                emit('handleClick');
                emit('update:visible', false);
            }
        } catch (e) {
            ElMessage.error(e.message);
        }
    });
};

// ========================= 验证码 =========================
let emailCode = ref('发送'); // 提示文字
let codeDisabled = ref(false); // 按钮控制
async function onSendCode() {
    try {
        if(!form.eMail) {
            ElMessage.error('请输入邮箱');
            return false;
        };
        codeDisabled.value = true; // 发送按钮控制
        let countDownNum = 60;// 倒计时
        countDown(countDownNum, (dataNum) => {
            if(typeof dataNum == "object") {
                emailCode.value = '发送';
                codeDisabled.value = false;
                return;
            };
            emailCode.value = dataNum;
        });
        // 验证码接口
        const res = await loginApi.emailSend({
            sendType:SEND_EMAIL_TYPE.UPDATE_EMAIL.value, // 更新邮箱
            eMail:form.eMail,
        });
        if(res.meta.status !== 200) throw new Error(res.meta.msg);
    } catch (e) {
        console.error(e);
        ElMessage.error(e.message);
    };
};

// 重置表单
function resetForm() {
    formRef.value.resetFields(); // 重置表单
    emailCode.value = '发送';
    clearCountDown();
};
</script>

<style lang="scss" scoped>

</style>